import os
import data
import logging
from pyglet.gl import *
import ctypes
from main import Enemy
fourfv = ctypes.c_float * 4

#Global variables
global		enemy_counter
global		score
score		= 0
state 		= None
window 		= None
mouse		= None
enemy_counter   = 0


def resize(widthWindow, heightWindow):
	"""Initial settings for the OpenGL state machine, clear color, window size, etc"""
	glEnable(GL_BLEND)
	glEnable(GL_POINT_SMOOTH)
	glShadeModel(GL_SMOOTH)# Enables Smooth Shading
	glBlendFunc(GL_SRC_ALPHA,GL_ONE)#Type Of Blending To Perform
	glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);#Really Nice Perspective Calculations
	glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);#Really Nice Point Smoothing
	glDisable(GL_DEPTH_TEST)


def init():
	global window
	window = pyglet.window.Window(resizable=True, visible=False)
	window.clear()
	window.resize = resize
	window.set_visible(True)
	window.resize(window.width, window.height)
	enemy_counter	= 0
	score		= 0
	global state
	state = GameState()
	global mouse
	mouse		= Mouse()
	global images
	data.loadimages() #sound('whistle_ding.mp3').
	images = data._images
	#image_path = os.path.join('images')
	#images = [os.path.join(image_path, f) for f in os.listdir(image_path) if f.endswith('.png')]
	#images = [pyglet.image.load(path) for path in images]

class Mouse:
	def __init__(self):
		self.objects = []
		self.moving_objects = [] 
		state.add_handler(self)
		self.selected_object	= None

	def add_object(self, object):
		self.objects.append(object)

	def remove_object(self, robject):
		for object in self.objects:
			if object.name == robject.name:
				del self.objects[self.objects.index(object)]

#	def on_mouse_release(self, x, y, button, modifiers):
#		for object in self.objects:
#			if object.selected(x, y):
#				object.damage(50)

	def on_mouse_press(self, x, y, button, modifiers):
		for object in self.objects:
			catch = object.selected(x, y)
			if catch:
				print "click caught ", catch
				object.die()#.damage(50)
				return pyglet.event.EVENT_HANDLED
			else:
				print "click not caught, ", catch

class GameState(pyglet.event.EventDispatcher):
	def __init__(self):
		self.time = 0
		self.window = window
		window.push_handlers(self)
		pyglet.clock.schedule_interval(self.update, 1.0/60)
		pyglet.clock.schedule_interval(self.spawn_enemy, 2)

	def spawn_enemy(self, dt):
		#enemy = Enemy( 30, 210, health = 10, destx=670, desty=480, images = images)
		enemy = Enemy( 80, 200, health = 10, destx=650, desty=490, images = images)

	def add_handler(self, handler):
		'''Add an event handler to the gamestate.
		event handlers are objects which accept and generate events'''
		if handler != None:
			self.push_handlers(handler)
		else:
			#Add a log/error message?
			pass

	def add_enemy(self, object):
		self.add_handler(object)
		mouse.add_object(object)

	def update(self, dt):
		self.time += dt
		self.dispatch_event('on_update', dt)
		if score < 0:
			print "Game over"
			exit()

	# Relay many window events to our child handlers
	def on_draw(self, *args):
		window.clear()
		self.relay_event('on_draw', *args)

	def on_key_press(self, *args):
		self.relay_event('on_key_press', *args)
	
	def on_key_release(self, *args):
		self.relay_event('on_key_release', *args)
	
	def on_mouse_motion(self, *args):
		self.relay_event('on_mouse_motion', *args)

	def on_mouse_press(self, *args):
		self.relay_event('on_mouse_press', *args)

	def relay_event(self, event_type, *args):
		'''Similar to dispatch_event, only it does not call the event
		handler on the dispatcher itself, which is not deisired for relaying.

		:Parameters:
			`event_type` : str
				Name of the event.
			`args` : sequence
				Arguments to pass to the event handler.
		'''
		assert event_type in self.event_types

		# Search handler stack for matching event handlers
		for frame in list(self._event_stack):
			handler = frame.get(event_type, None)
			if handler:
				try:
					if handler(*args):
						return
				except TypeError:
					self._raise_dispatch_exception(event_type, args, handler)

GameState.register_event_type('on_key_press')
GameState.register_event_type('on_key_release')
GameState.register_event_type('on_mouse_motion')
GameState.register_event_type('on_mouse_press')
GameState.register_event_type('on_draw')
GameState.register_event_type('on_update')

if __name__ == '__main__':
		init()
		pyglet.app.run()

